package com.iotboss.system.service.impl;

import com.alibaba.fastjson2.JSON;
import com.iotboss.common.core.domain.entity.SysUser;
import com.iotboss.common.mapper.mysql.IotDeviceMapper;
import com.iotboss.common.mapper.mysql.deptUtilMapper;
import com.iotboss.common.utils.PageUtil;
import com.iotboss.common.utils.Upload;
import com.iotboss.common.mapper.mysql.orUtilMapper.IotOrDeviceMapper;
import com.iotboss.system.service.IIotDeviceService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 在线用户 服务层处理
 *
 * @author iotboss
 */
@Service
public class IIotDeviceServiceImpl implements IIotDeviceService
{

    @Resource
    RabbitTemplate rabbitTemplate;
    @Resource
    IotOrDeviceMapper orDeviceMapper;
    @Resource
    IotDeviceMapper iotDeviceMapper;
    @Override
    public String importDeviceByExcl(MultipartFile file, SysUser User) {
        String filename = file.getOriginalFilename();
        String ReadName = UUID.randomUUID().toString().replace("-", "") + filename;
        String newName = UUID.randomUUID().toString().replace("-", "") + "_DeviceImport";
        String flieUrlRx = "/mnt/file/";
        ReadName = flieUrlRx + ReadName;
        try{
            File file2 = new File("");
            String filePath = file2.getCanonicalPath();
            File newFile = new File(filePath + ReadName );
            File Url = new File(filePath + flieUrlRx +"1.txt");//tomcat 生成路径
            Upload.mkdirsmy(Url);
            file.transferTo(newFile);
            // 创建队列
            String polling_queueName = "admin_saveDevice_queue";
            String polling_routingKey = "admin.saveDevice.queue";
            String polling_exchangeName = "admin_exchange";//路由
            //创建参数map
            Map<String, Object> start_type = new HashMap<>();
            start_type.put("type", "importDeviceData");//启动类型
            start_type.put("filePath", filePath);//项目根目录
            start_type.put("ReadName", ReadName);//上传新文件名
            start_type.put("newName", newName);//输出文件名
            start_type.put("User", User);//登录用户信息
            /***
             * 队列上传成功 ->在消费者 创建 执行结果记录 及 提供执行结果文件下载路径
             */
            //新增操作记录
            Map<String, Object> orMap = new HashMap<String, Object>();
            orMap.put("useId",User.getUserId());
            orMap.put("deptId",User.getDeptId());
            orMap.put("type","0");
            orMap.put("filePath",filePath+ReadName);
            int id = orDeviceMapper.insert(orMap);
            start_type.put("id", orMap.get("id"));//将操作记录在数据库中的id放入 map 方便 消费者消费结束后 将 消费结果插入
            rabbitTemplate.convertAndSend(polling_exchangeName, polling_routingKey, JSON.toJSONString(start_type),message -> {
                // 设置消息过期时间 30 分钟 过期
                message.getMessageProperties().setExpiration("" + (30 * 1000 * 60));
                return message;
            });

        }catch(Exception e){
        e.printStackTrace();
        }
        return null;
    }
    @Resource
    private deptUtilMapper deptUtilMapper;

    @Override
    public Map<String, Object> getList(Map<String, Object> map) { //  获取列表
        Integer currenPage = map.get("pageNum") != null ? Integer.parseInt(map.get("pageNum").toString()) : 0;
        Integer pageSize = map.get("pageSize") != null ? Integer.parseInt(map.get("pageSize").toString()) : 10;
        Integer rowCount = null; // mapper查询个数
        PageUtil pu = null;
        rowCount = rowCount != null ? rowCount : 0;
        pu = new PageUtil(rowCount, currenPage, pageSize);//初始化分页工具类
        String admin = "100";//总企业dept_id todo
        String dept_id = map.get("dept_id").toString();
        Map<String, Object> rMap = new HashMap<>();
        if (map.get("dept_id").toString().equals(admin)){//判断
            rowCount = iotDeviceMapper.selCountAdmin(map);
            rowCount = rowCount != null ? rowCount : 0;
            pu = new PageUtil(rowCount, currenPage, pageSize);//初始化分页工具类
            map.put("StarRow", pu.getStarRow());
           //map.put("PageSize", pu.getPageSize());
            List<Map<String, Object>> adminList = iotDeviceMapper.selListAdmin(map);

            rMap.put("data",adminList);
            return rMap;
        }else {//不是 总企业
        //查询所有 子企业以及本企业的depi_id
            Map<String, Object> dept = new HashMap<>();
            List<String> deptList = deptUtilMapper.selSonDept(dept);//子企业id 包含本企业
            map.put("depts",deptList);
            rowCount = iotDeviceMapper.selCount(map);
            rowCount = rowCount != null ? rowCount : 0;
            pu = new PageUtil(rowCount, currenPage, pageSize);//初始化分页工具类
            map.put("StarRow", pu.getStarRow());
            map.put("PageSize", pu.getPageSize());
            List<Map<String, Object>> list = iotDeviceMapper.selList(map);
            rMap.put("data",list);
            return rMap;
        }

    }
}
